#include "Col.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "Class.h"
#include "SimpleHashTable.h"

//---- SimpleHashTable ---------------------------------------------------------

NewMetaImpl(SimpleHashTable, HashTable, (TVP(tab, capacity)));

SimpleHashTable::SimpleHashTable(pEqualFunc eq, pHashFunc hs, pHashFunc exhs,
				pEqualFunc exef, int initCap) : HashTable(initCap, eq, hs, 0)
{
	extKeyHash= exhs;
	extKeyEqual= exef;
	tab= new Object* [capacity+1];
}

SimpleHashTable::~SimpleHashTable()
{
	SafeDelete(tab);
}

void *SimpleHashTable::ExtKeyFind(void *p)
{
	register void *op;
	
	int slot= (int) (extKeyHash(p) % capacity);
	while ((op= KeyAt(slot)) && ! extKeyEqual(p, op))
		if (++slot == capacity)
			slot= 0;
	return op;
}

void SimpleHashTable::Empty(int newCapacity)
{
	SafeDelete(tab);
	CalcBounds(newCapacity);
	tab= new Object* [capacity+1];
	*size= 0;
	Changed();
}

void SimpleHashTable::FreeAll()
{
	for (int i= 0; i <= capacity; i++)
		SafeDelete(tab[i]);
}

void* SimpleHashTable::LinearSearch(void* p)
{
	register int i;
	register void* ip;
	
	for (i= 0; i <= capacity; i++) {
		ip= tab[i];
		if (ip && equal(ip, p))
			return ip;
	}
	return 0;
}

//---- table primitives ----

void *SimpleHashTable::KeyAt(int i)
{
	return tab[i];
}

void SimpleHashTable::SetKeyAt(void *obj, int i)
{
	tab[i]= (Object*)obj;
}

void SimpleHashTable::NullAt(int i)
{
	tab[i]= 0;
}

void SimpleHashTable::Swap(int i, int j)
{
	void *val= tab[i];
	tab[i]= tab[j];
	tab[j]= (Object*) val;
}

HashTable *SimpleHashTable::MakeNew(int initCap)
{
	return new SimpleHashTable(equal, hash, extKeyHash, extKeyEqual, initCap);
}

void SimpleHashTable::Assign(HashTable *ht)
{
	SimpleHashTable* sht= (SimpleHashTable*)ht;
	
	HashTable::Assign(ht);
	SafeDelete(tab);
	tab= sht->tab;
	sht->tab= 0;
}

